package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.cache.redis.RedisKeyBuilder;
import com.gitee.apanlh.util.cache.redis.api.RedisString;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeYuanRongHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.*;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 安心分期出-V2&8位源融花28
 * @ Author WJB
 * 渠道方对接- API全流程（掩码+MD5）
 * 链接：https://apifox.com/apidoc/shared-919fdeb7-8c82-4b87-985b-ae85a068b965?pwd=WOvHr1sA
 */
@ApiPlan(productId = "332", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatYuanRongHuaPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    public static final String KEY = "S0yk7dQJVW1Kz4n0";
    public static final String CHANNEL_ID = "20233057";
    public static final RedisString PLAN_MATCH_GOODS_ID = RedisKeyBuilder.builder().withKeys("temp_yuan_rong_hua").buildString();

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeYuanRongHua data = new ApiPlatDataExchangeYuanRongHua();
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(30000);
        data.setLoadAmount(money);
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 4)
                .end(1);
        data.setZhima(zhima);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 3)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 3)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 3)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 3)
                .end(1);
        data.setHouse(house);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 3)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 3)
                .end(1);
        data.setCar(car);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 3)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 3)
                .end(1);
        data.setPubFund(gongjijin);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 3)
                .end(1);
        data.setGuarantor(baodanIs);
        // 逾期
        Integer overdue = ChooseEq.create(apiDataExchangeParameter.getOverdue())
                .when("1", 2)
                .when("2", 3)
                .when("3", 4)
                .end(1);
        data.setCreditRecord(overdue);
        // 信用卡
        Integer creditLimit = ChooseEq.create(apiDataExchangeParameter.getCreditLimit())
                .when("1", 1)
                .when("2", 2)
                .when("3", 2)
                .when("4", 2)
                .when("5", 2)
                .when("6", 2)
                .end(1);
        data.setCreditCard(creditLimit);
        // 社保
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 3)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 3)
                .end(1);
        data.setSocialSecurity(shebao);
        // 微粒贷
        data.setWeilidai(1);
        // 借款期限
        Integer loan = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "1", 1)
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 4)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 5)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 5)
                .when(apiDataExchangeParameter.getLoanTerm(), "6", 6)
                .end(1);
        data.setTerm(loan);
        // 白条
        Integer bt = ChooseEq.create(apiDataExchangeParameter.getBtLimit())
                .when("1", 1)
                .when("2", 2)
                .when("3", 3)
                .when("4", 4)
                .when("5", 4)
                .end(1);
        data.setBaitiao(bt);
        //  职业
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 4)
                .when(apiDataExchangeParameter.getCareer(), "3", 2)
                .when(apiDataExchangeParameter.getCareer(), "4", 1)
                .when(apiDataExchangeParameter.getCareer(), "5", 3)
                .end(1);
        data.setWork(job);
        //  贷款用途
        Integer loanUse = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanPurpose(), "1", 3)
                .when(apiDataExchangeParameter.getLoanPurpose(), "2", 4)
                .when(apiDataExchangeParameter.getLoanPurpose(), "3", 5)
                .when(apiDataExchangeParameter.getLoanPurpose(), "4", 2)
                .when(apiDataExchangeParameter.getLoanPurpose(), "5", 1)
                .when(apiDataExchangeParameter.getLoanPurpose(), "6", 1)
                .end(1);
        data.setPurpose(loanUse);
        //  收入情况
        Integer salaryPayMethod = ChooseEq.create()
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "1", 2)
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "2", 1)
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "3", 2)
                .end(1);
        data.setSalarySettleType(salaryPayMethod);
        //  学历
        Integer educationAttainment = ChooseEq.create()
                .when(apiDataExchangeParameter.getEducationAttainment(), "1", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "2", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "3", 1)
                .when(apiDataExchangeParameter.getEducationAttainment(), "4", 2)
                .when(apiDataExchangeParameter.getEducationAttainment(), "5", 3)
                .when(apiDataExchangeParameter.getEducationAttainment(), "6", 3)
                .end(1);
        data.setEducation(educationAttainment);
        //  月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiDataExchangeParameter.getMonthlySalary(), "1", 1000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "2", 3000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "3", 8000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "4", 15000)
                .when(apiDataExchangeParameter.getMonthlySalary(), "5", 30000)
                .end(5500);
        data.setMonthIncome(monthlySalary);

        //  性别 1男 2女
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .end(1);

        AES aes = AES.createEcb(KEY.getBytes());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("version", "1.0.0");
        dataMap.put("timestamp", System.currentTimeMillis() / 1000);
        dataMap.put("mobile", apiDataExchangeParameter.getPhoneMd5());
        dataMap.put("username", "测试用户");
        dataMap.put("age", ClassConvertUtils.toInt(apiDataExchangeParameter.getAge()));
        dataMap.put("sex", sex);
        dataMap.put("city", apiDataExchangeParameter.getCity());
        dataMap.put("mobilePlatform", "android");
        dataMap.put("ip", apiDataExchangeParameter.getIp());
        dataMap.put("fieldInfo", data);

        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(dataMap));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("accountNo", CHANNEL_ID);
            newMap.put("data", dataStr);
        });

        return JsonUtils.toJson(map);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        String applyId = apiApplyParameter.dataExchangeApplyId();
        List<Object> list = new ArrayList<>();
        list.add(ApiPlatYuanRongHuaPhoneMd5Convert.PLAN_MATCH_GOODS_ID.get(applyId, String.class));

        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("version", "1.0.0");
        dataMap.put("timestamp", System.currentTimeMillis() / 1000);
        dataMap.put("mobile", apiApplyParameter.getPhone());
        dataMap.put("username", apiApplyParameter.getUserName());
        dataMap.put("matchId", apiApplyParameter.dataExchangeApplyId());
        dataMap.put("planMatchGoodsId", list);
        dataMap.put("ip", apiApplyParameter.getIp());

        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(dataMap));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("accountNo", CHANNEL_ID);
            newMap.put("data", dataStr);
        });

        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONArray planMatchGoods = resData.getJSONArray("planMatchGoods");
        if (ValidParam.isEmpty(planMatchGoods)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONArray protocolList = resData.getJSONArray("protocolList");

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        BigDecimal price = resData.getBigDecimal("price");
        String orderId = resData.getString("matchId");
        JSONObject item = planMatchGoods.getJSONObject(0);
        if (ValidParam.isNotNull(item)) {
            String companyName = item.getString("planMatchOrgansName");
            String productName = item.getString("planMatchGoodsName");
            String logo = item.getString("planMatchGoodsLogo");
            String planMatchGoodsId = item.getString("planMatchGoodsId");

            List<ApiProtocol> apiProtocols = CollUtils.newArrayList(newList -> {
                //  获取协议
                IteratorUtils.array(protocolList, (protocolResult, index) -> {
                    JSONObject protocolObject = protocolList.getJSONObject(index);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("protocolName"));
                    protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                    newList.add(protocol);
                });
            });

            result.setPrice(price);
            result.setLogoPath(logo);
            result.setDisplayName(companyName);
            result.setProductName(productName);
            result.setApplyId(orderId);
            result.setProtocolList(apiProtocols);
            ApiPlatYuanRongHuaPhoneMd5Convert.PLAN_MATCH_GOODS_ID.setForMinutes(orderId, planMatchGoodsId, 10L);
        }
        return result;
    }


    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

}
